<template>
	<view>
		<view class="circle">
			<!-- <view class="houseId row-center">
				{{ show_nfcId ? '鸽舍号：' + show_nfcId : '鸽舍号' }}
			</view> -->
			<proportion :leftValue="stayCount" :rightValue="whipCount"></proportion>
			
			<!-- 数据加载状态 -->
			<view v-if="isLoading" class="loading-data">
				<u-loading mode="circle" size="40"></u-loading>
				<text>数据加载中...</text>
			</view>
			
			<!-- 有数据时显示 -->
			<view v-else-if="cageStatu && cageStatu.length" class="ul">
				<view class="li" v-for="(item, index) in cageStatu" :key="`cage-${item.cage_id}-${index}`">
					<view class="left">
						<span class="cageId">{{ item.cage_id }}</span>
						<span class="statu">{{ item.statu }}</span>
					</view>

					<view class="right" v-if="stayNum.length > 0">
						<button class="number" v-for="item_child in num" :key="`cage-${item.cage_id}-btn-${item_child}`"
							@click="handleClick(item.cage_id, item_child)"
							:class="getButtonClass(item.cage_id, item_child)">
							{{ item_child }}
						</button>
					</view>
				</view>
			</view>
			
			<!-- 无数据状态 -->
			<view v-else-if="cageStatu && cageStatu.length === 0" class="no-data">
				<text>暂无数据</text>
			</view>
		</view>
		<!-- 顶部提示 -->
		<u-toast ref="uToast" />
		<!-- 加载状态 -->
		<u-loading v-if="isLoading"></u-loading>
	</view>
</template>

<script>
import {
	reqFeedBirds,
	reqGetStatu,
	reqStayNum
} from '@/api/index.js'
import {
	getNowDate
} from '@/getTime.js'
import {
	mapGetters
} from 'vuex'
import {
	debounce
} from '@/utils/debounce.js'

export default {
	data() {
		return {
			baseFormData: {
				siteId: '',
				houseId: '',
				cageId: '',
				cubNumber: 0,
				cubTime: null
			},
			num: [1, 2, 3, 4, 0],
			stayNum: [],
			isLoading: false,
			isSubmitting: false
		};
	},
	
	// 修改 mounted 生命周期
	async mounted() {
		this.isLoading = true;
		try {
			await this.getStatu();  // 获取鸽笼状态
			await this.getStay();   // 获取留窝数据
		} catch (error) {
			console.error('初始化失败:', error);
			this.$refs.uToast.show({
				title: '页面加载失败',
				type: 'error',
				duration: 1500
			});
		} finally {
			this.isLoading = false;
		}
	},
	
	computed: {
		...mapGetters(['nfcId', 'show_nfcId', 'cageStatu', 'whipCount', 'stayCount'])
	},
	
	watch: {
		// 监听当前的nfcId，一旦改变就重新获取鸽笼状态
		async nfcId(newValue, oldValue) {
			if (oldValue !== newValue) {
				this.isLoading = true;
				try {
					await this.getStatu();
					await this.getStay();
				} catch (error) {
					console.error('nfcId变化时加载失败:', error);
					this.$refs.uToast.show({
						title: '数据更新失败',
						type: 'error',
						duration: 1500
					});
				} finally {
					this.isLoading = false;
				}
			}
		},
	},
	
	methods: {
		// 获取鸽笼状态（与查蛋页面相同的方法）
		async getStatu() {
			console.log('调仔页面 - 获取鸽笼状态');
			const obj = {
				siteId: uni.getStorageSync('siteId'),
				houseId: this.nfcId,
			}
			console.log('获取鸽笼状态参数:', obj);
			await this.$store.dispatch('getStatu', obj);
		},
		
		// 安全获取按钮样式类的方法
		getButtonClass(cageId, number) {
			if (!this.stayNum || !Array.isArray(this.stayNum)) {
				return '';
			}
			
			const cageIndex = cageId - 1;
			if (cageIndex < 0 || cageIndex >= this.stayNum.length) {
				console.warn(`cageId ${cageId} 超出 stayNum 数组范围`);
				return '';
			}
			
			const cageData = this.stayNum[cageIndex];
			if (!cageData) {
				console.warn(`cageId ${cageId} 对应的数据为 undefined`);
				return '';
			}
			
			const cageNumber = cageData.number;
			if (cageNumber === undefined || cageNumber === null) {
				console.warn(`cageId ${cageId} 的number属性为 undefined 或 null`);
				return '';
			}
			
			return number === cageNumber ? 'ycd_button_right' : '';
		},
		
		// 处理点击事件
		async handleClick(cageId, number) {
			if (this.isSubmitting) {
				return;
			}
			
			this.isSubmitting = true;
			
			try {
				this.baseFormData.siteId = uni.getStorageSync('siteId');
				this.baseFormData.houseId = this.nfcId;
				this.baseFormData.cubNumber = number;
				this.baseFormData.cageId = cageId;
				this.baseFormData.cubTime = getNowDate();
				
				this.$loading();
				
				const data = await reqFeedBirds(this.baseFormData);
				
				if (data.code === 200) {
					const { siteId, houseId } = this.baseFormData;
					const obj = { siteId, houseId };
					
					// 更新鸽笼状态
					await this.$store.dispatch('getStatu', obj);
					// 更新留窝数据
					await this.getStay();
					// 更新比例
					await this.getPR();
					
					this.$refs.uToast.show({
						title: `成功调为${number}个仔`,
						type: 'success',
						duration: '600',
						position: 'top'
					});
				} else if (data.code === 404) {
					this.$refs.uToast.show({
						title: data.msg,
						type: 'warning',
						duration: '800',
						position: 'top'
					});
				}
			} catch (error) {
				console.error('handleClick error:', error);
				this.$refs.uToast.show({
					title: '操作失败',
					type: 'error',
					duration: '800',
					position: 'top'
				});
			} finally {
				this.$hide();
				this.isSubmitting = false;
			}
		},
		
		// 获取停留数量
		async getStay() {
			try {
				const obj = {
					siteId: uni.getStorageSync('siteId'),
					houseId: this.nfcId
				};
				
				const res = await reqStayNum(obj);
				
				if (res.code === 200) {
					this.stayNum = res.cages;
				} else {
					this.$refs.uToast.show({
						title: '获取留窝数据失败',
						type: 'error',
						duration: '800',
						position: 'top'
					});
				}
			} catch (error) {
				console.error('getStay error:', error);
				this.$refs.uToast.show({
					title: '获取留窝数据失败',
					type: 'error',
					duration: '800',
					position: 'top'
				});
			}
		},
		
		// 获取当天留窝抽蛋比例
		async getPR() {
			try {
				if (uni.getStorageSync('siteId')) {
					const obj = {
						site_id: uni.getStorageSync('siteId')
					};
					await this.$store.dispatch('getEWPR', obj);
				}
			} catch (error) {
				console.error('getPR error:', error);
			}
		},
		
		toExp() {
			uni.navigateTo({
				url: '/pages/expection/expection'
			});
		}
	}
}
</script>

<style lang="scss">
@import 'styles/builder.scss';

.checked_border {
	background-color: #fff;
	color: lawngreen;
	border: 2px solid greenyellow;
}

.ycd_bg {
	background-color: #dbe2f1;
}

.ycd_color {
	color: #4472c4
}

.ycd_color_left {
	color: #7d9ad2;
	border-right: 2px solid #7c9bd2;
}

.ycd_button_right {
	color: #dbe2f1;
	background-color: #7c9bd2;
}

.other_bg {
	background-color: #7c9bd2;
}

.other_color_left {
	color: #dbe2f1;
	border-right: 2px solid #dbe2f1;
}

.other_button_right {
	color: #7c9bd2;
	background-color: #dbe2f1;
}

.houseId {
	width: 100%;
	margin: 10rpx auto;
	padding: 18.12rpx 18.12rpx;
	font-size: 39.86rpx;
	border-radius: 14.49rpx;
	color: #fff;
	background-color: #7d9ad2;
}

.circle {
	width: 100%;
	height: 100vh;

	h1 {
		text-align: center;
		font-weight: 700;
	}

	 .ul {
	    display: flex;
	    /* 关键：从纵向排列改为横向排列 */
	    flex-direction: row; 
	    justify-content: space-around;
	    align-content: space-around;
	    width: 100%;
	    height: 70%;
	    flex-wrap: wrap; /* 保持换行 */
	    margin-top: 20rpx;
	  
	
	  .li {
	    display: flex;
	    justify-content: space-around;
	    /* 关键：宽度调整为 ~45%，确保一行两个 */
	    width: 45%; 
	    height: 30%;
	    text-align: center;
	    align-items: center;
	    border-radius: 20rpx;
	    background-color: #dbe2f1; /* 保留原有蓝色笼子背景 */

			.left,
			.right {
				display: flex;
				flex-direction: column;
				justify-content: space-around;
				height: 90%;
				font-weight: bold;
			}

			.left {
				width: 33%;
				justify-content: center;
				border-right: 2px solid #7c9bd2;
				box-sizing: border-box;
				color: #4472c4;

				.cageId {
					font-size: 100rpx
				}

				.statu {
					font-size: 20rpx;
				}
			}

			.right {
				width: 66%;
				display: flex;
				flex-direction: row;
				justify-content: space-around;
				align-content: space-around;
				flex-wrap: wrap;

				button {
					display: inline-block;
				}

				.number {
					@include flex(center, center, 'items');
					width: 40%;
					height: 30%;
					font-size: 41.16rpx;
					font-weight: bold;
					border-radius: 10rpx;
					box-sizing: border-box;
					border: 1px solid #7c9bd2;

					&:last-child {
						width: 80%;
						height: 24%;
					}
				}

				.submit {
					width: 80%;
					font-size: 20rpx;
					font-weight: bold;
					border-radius: 10rpx;
				}
			}
		}
	}
	
	// 添加加载状态和无数据状态的样式
	.loading-data, .no-data {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 200rpx;
		font-size: 32rpx;
		color: #999;
		flex-direction: column;
		
		text {
			margin-top: 20rpx;
		}
	}
}

.abnormal {
	@include flex(space-around, center, 'items');
	width: 70%;
	height: 120rpx;
	margin: 0 auto;
	padding: 20rpx 57.97rpx;
	font-size: 38.04rpx;
	font-weight: 700;
	color: #fff;
	box-shadow: 9px 4px 10px 0 #7d9ad2;
	background-color: #7d9ad2;
}

@include responseTo('phone') {
	.circle .ul .li .left .statu {
		font-size: 36rpx;
	}
}
</style>